package com.frxuexi.park2305.notice

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.NoticeBeanItem
import com.frxuexi.lib_base.http.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import java.lang.Exception

class NoticeDataSource(val apiService: ApiService):PagingSource<Int,NoticeBeanItem> (){
    override fun getRefreshKey(state: PagingState<Int, NoticeBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeBeanItem> {
        return withContext(Dispatchers.IO){
            try {
                val page=params.key?:0
                val res = apiService.getNotices(page).first()
                if(res.code==200){
                    val nextPage=if(res.data.size==10) page+1 else null
                    LoadResult.Page(res.data,null,nextPage)
                }else{
                    LoadResult.Error(Exception(res.message))
                }

            }catch (e:Exception){
                LoadResult.Error(e)
            }
        }
    }
}